<?php
namespace app;

use app\common\exception\Client;
use app\common\exception\Server;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\Handle;
use think\exception\HttpException;
use think\exception\HttpResponseException;
use think\exception\ValidateException;
use think\facade\Config;
use think\Response;
use Throwable;

/**
 * 应用异常处理类
 */
class ExceptionHandle extends Handle
{
    /**
     * 不需要记录信息（日志）的异常类列表
     * @var array
     */
    protected $ignoreReport = [
        HttpException::class,
        HttpResponseException::class,
        ModelNotFoundException::class,
        DataNotFoundException::class,
        ValidateException::class,
    ];

    /**
     * 记录异常信息（包括日志或者其它方式记录）
     *
     * @access public
     * @param  Throwable $exception
     * @return void
     */
    public function report(Throwable $exception): void
    {
        // 使用内置的方式记录异常日志

        // 优先检查dontReport标记
        if (method_exists($exception, 'dontReport') && $exception->dontReport()) {
            return;
        }

        // 服务端异常已自行记录，跳过默认记录
        if (!$exception instanceof Server) {
            parent::report($exception);
        }
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @access public
     * @param \think\Request   $request
     * @param Throwable $e
     * @return Response
     */
    public function render($request, Throwable $e): Response
    {
        // 添加自定义异常处理机制
        // 客户端异常
        if ($e instanceof Client) {
            return json([
                'errCode' => $e->errCode(),
                'msg'  => $e->getClientMessage(),
                'data' => json_decode($e->getMessage(), true)['data'] ?? []
            ], $e->getHttpCode());
        }

        // 其他异常（根据环境区分）
        if (Config::get('app.debug')) {
            return parent::render($request, $e);
        }

        // 服务端异常
        if ($e instanceof Server) {
            return json([
                'errCode' => 503,
                'msg'  => '系统维护中，请稍后再试'
            ], 503);
        }

        return json([
            'code' => 500,
            'msg'  => 'wangluocouwu'
        ], 500);
    }
}
